using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Page
{
    [Serializable()]
    public class PageDetail : Csla.BusinessBase<PageDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _pageid = Guid.NewGuid();
        private int _kbid = 0;
        private SmartDate _createdate = new SmartDate(DateTime.Now);
        private SmartDate _publishdate = new SmartDate(false);
        private SmartDate _expiredate = new SmartDate(false);
        private SmartDate _statusdate = new SmartDate(false);
        private Guid _currentuserid = Guid.NewGuid();
        private string _title = string.Empty;
        private string _desc = string.Empty;
        private int _ivAccessType = 0;
        private int _ivLevel = 0;
        private int _ivStatus = 0;
        private int _ivPriority = 0;
        private Guid _templateid = Guid.NewGuid();
        private string _keywords = string.Empty;
        private int _revision = 0;
        private int _ivItemtype = 1;
        private int _mode = 0;
        private string _summary = string.Empty;
        private Boolean _spotlight = false;
        private Int64 _views = 0;
        private int _comments = 0;
        private int _rank = 0;
        private Guid _userid = Guid.Empty;

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid pageid
        {
            get
            {
                CanReadProperty("pageid", true);
                return _pageid;
            }
            set
            {
                CanWriteProperty("pageid", true);
                if (!_pageid.Equals(value))
                {
                    _pageid = value;
                    PropertyHasChanged("pageid");
                }
            }
        }

        public int kbid
        {
            get
            {
                CanReadProperty("kbid", true);
                return _kbid;
            }
        }

        public DateTime createdate
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Date;
            }
        }

        public string createdateString
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Text;
            }
            set
            {
                CanWriteProperty("createdate", true);
                if (value == null)
                    value = string.Empty;
                if (!_createdate.Equals(value))
                {
                    _createdate.Text = value;
                    PropertyHasChanged("createdate");
                }
            }
        }

        public DateTime publishdate
        {
            get
            {
                CanReadProperty("publishdate", true);
                return _publishdate.Date;
            }
        }

        public string publishdateString
        {
            get
            {
                CanReadProperty("publishdate", true);
                return _publishdate.Text;
            }
            set
            {
                CanWriteProperty("publishdate", true);
                if (value == null)
                    value = string.Empty;
                if (!_publishdate.Equals(value))
                {
                    _publishdate.Text = value;
                    PropertyHasChanged("publishdate");
                }
            }
        }

        public DateTime expiredate
        {
            get
            {
                CanReadProperty("expiredate", true);
                return _expiredate.Date;
            }
        }

        public string expiredateString
        {
            get
            {
                CanReadProperty("expiredate", true);
                return _expiredate.Text;
            }
            set
            {
                CanWriteProperty("expiredate", true);
                if (value == null)
                    value = string.Empty;
                if (!_expiredate.Equals(value))
                {
                    _expiredate.Text = value;
                    PropertyHasChanged("expiredate");
                }
            }
        }

        public DateTime statusdate
        {
            get
            {
                CanReadProperty("statusdate", true);
                return _statusdate.Date;
            }
        }

        public string statusdateString
        {
            get
            {
                CanReadProperty("statusdate", true);
                return _statusdate.Text;
            }
            set
            {
                CanWriteProperty("statusdate", true);
                if (value == null)
                    value = string.Empty;
                if (!_statusdate.Equals(value))
                {
                    _statusdate.Text = value;
                    PropertyHasChanged("statusdate");
                }
            }
        }

        public Guid currentuserid
        {
            get
            {
                CanReadProperty("currentuserid", true);
                return _currentuserid;
            }
            set
            {
                CanWriteProperty("currentuserid", true);
                if (!_currentuserid.Equals(value))
                {
                    _currentuserid = value;
                    PropertyHasChanged("currentuserid");
                }
            }
        }

        public string title
        {
            get
            {
                CanReadProperty("title", true);
                return _title;
            }
            set
            {
                CanWriteProperty("title", true);
                if (value == null)
                    value = string.Empty;
                if (!_title.Equals(value))
                {
                    _title = value;
                    PropertyHasChanged("title");
                }
            }
        }

        public string desc
        {
            get
            {
                CanReadProperty("desc", true);
                return _desc;
            }
            set
            {
                CanWriteProperty("desc", true);
                if (value == null)
                    value = string.Empty;
                if (!_desc.Equals(value))
                {
                    _desc = value;
                    PropertyHasChanged("desc");
                }
            }
        }

        public int IvAccessType
        {
            get
            {
                CanReadProperty("IvAccessType", true);
                return _ivAccessType;
            }
            set
            {
                CanWriteProperty("IvAccessType", true);
                if (!_ivAccessType.Equals(value))
                {
                    _ivAccessType = value;
                    PropertyHasChanged("IvAccessType");
                }
            }
        }

        public int IvLevel
        {
            get
            {
                CanReadProperty("IvLevel", true);
                return _ivLevel;
            }
            set
            {
                CanWriteProperty("IvLevel", true);
                if (!_ivLevel.Equals(value))
                {
                    _ivLevel = value;
                    PropertyHasChanged("IvLevel");
                }
            }
        }

        public int IvStatus
        {
            get
            {
                CanReadProperty("IvStatus", true);
                return _ivStatus;
            }
            set
            {
                CanWriteProperty("IvStatus", true);
                if (!_ivStatus.Equals(value))
                {
                    _ivStatus = value;
                    PropertyHasChanged("IvStatus");
                }
            }
        }

        public int IvPriority
        {
            get
            {
                CanReadProperty("IvPriority", true);
                return _ivPriority;
            }
            set
            {
                CanWriteProperty("IvPriority", true);
                if (!_ivPriority.Equals(value))
                {
                    _ivPriority = value;
                    PropertyHasChanged("IvPriority");
                }
            }
        }

        public Guid templateid
        {
            get
            {
                CanReadProperty("templateid", true);
                return _templateid;
            }
            set
            {
                CanWriteProperty("templateid", true);
                if (!_templateid.Equals(value))
                {
                    _templateid = value;
                    PropertyHasChanged("templateid");
                }
            }
        }

        public string keywords
        {
            get
            {
                CanReadProperty("keywords", true);
                return _keywords;
            }
            set
            {
                CanWriteProperty("keywords", true);
                if (value == null)
                    value = string.Empty;
                if (!_keywords.Equals(value))
                {
                    _keywords = value;
                    PropertyHasChanged("keywords");
                }
            }
        }

        public int revision
        {
            get
            {
                CanReadProperty("revision", true);
                return _revision;
            }
            set
            {
                CanWriteProperty("revision", true);
                if (!_revision.Equals(value))
                {
                    _revision = value;
                    PropertyHasChanged("revision");
                }
            }
        }

        public int IvItemtype
        {
            get
            {
                CanReadProperty("IvItemtype", true);
                return _ivItemtype;
            }
            set
            {
                CanWriteProperty("IvItemtype", true);
                if (!_ivItemtype.Equals(value))
                {
                    _ivItemtype = value;
                    PropertyHasChanged("IvItemtype");
                }
            }
        }

        public int Mode
        {
            get
            {
                CanReadProperty("Mode", true);
                return _mode;
            }
            set
            {
                CanWriteProperty("Mode", true);
                if (!_mode.Equals(value))
                {
                    _mode = value;
                    PropertyHasChanged("Mode");
                }
            }
        }

        public string summary
        {
            get
            {
                CanReadProperty("summary", true);
                return _summary;
            }
            set
            {
                CanWriteProperty("summary", true);
                if (value == null)
                    value = string.Empty;
                if (!_summary.Equals(value))
                {
                    _summary = value;
                    PropertyHasChanged("summary");
                }
            }
        }

        //public int Spotlight
        //{
        //    get
        //    {
        //        CanReadProperty("Spotlight", true);
        //        return _spotlight;
        //    }
        //    set
        //    {
        //        CanWriteProperty("Spotlight", true);
        //        if (!_spotlight.Equals(value))
        //        {
        //            _spotlight = value;
        //            PropertyHasChanged("Spotlight");
        //        }
        //    }
        //}

        public Boolean Spotlight
        {
            get
            {
                return _spotlight;
            }
            set
            {
                CanWriteProperty("Spotlight", true);
                if (!_spotlight.Equals(value))
                {
                    _spotlight = value;
                    PropertyHasChanged("Spotlight");
                }
            }
        }

        public Int64 Views
        {
            get
            {
                return _views;
            }
            set
            {
                CanWriteProperty("Views", true);
                if (!_views.Equals(value))
                {
                    _views = value;
                    PropertyHasChanged("Views");
                }
            }
        }

        public int Comments
        {
            get
            {
                return _comments;
            }
            set
            {
                CanWriteProperty("Comments", true);
                if (!_comments.Equals(value))
                {
                    _comments = value;
                    PropertyHasChanged("Comments");
                }
            }
        }

        public int Rank
        {
            get
            {
                return _rank;
            }
            set
            {
                CanWriteProperty("Rank", true);
                if (!_rank.Equals(value))
                {
                    _rank = value;
                    PropertyHasChanged("Rank");
                }
            }
        }

        public Guid Userid
        {
            get
            {
                CanReadProperty("Userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("Userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("Userid");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _pageid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // createdate
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "createdateString");
            //
            // title
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "title");
            ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("title", 4000));
            //
            // desc
            //
            ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("desc", 8000));
            //
            // keywords
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "keywords");
            ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("keywords", 4000));
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in pageDetail
            //AuthorizationRules.AllowRead("pageid", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("kbid", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("createdate", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("publishdate", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("expiredate", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("statusdate", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("currentuserid", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("title", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("desc", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("IvAccessType", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("IvLevel", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("IvStatus", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("IvPriority", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("templateid", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("keywords", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("privaterank", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("publicrank", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("revision", "pageDetailReadGroup");
            //AuthorizationRules.AllowRead("IvItemtype", "pageDetailReadGroup");

            //AuthorizationRules.AllowWrite("createdate", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("publishdate", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("expiredate", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("statusdate", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("currentuserid", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("title", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("desc", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("IvAccessType", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("IvLevel", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("IvStatus", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("IvPriority", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("keywords", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("privaterank", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("publicrank", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("revision", "pageDetailWriteGroup");
            //AuthorizationRules.AllowWrite("IvItemtype", "pageDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in pageDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("pageDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in pageDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("pageDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in pageDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("pageDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in pageDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("pageDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private PageDetail()
        { /* require use of factory method */
        }

        public static PageDetail NewPageDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a pageDetail");
            return DataPortal.Create<PageDetail>();
        }

        public static PageDetail GetPageDetail(Guid pageid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a pageDetail");
            return DataPortal.Fetch<PageDetail>(new Criteria(pageid));
        }

        public static void DeletePageDetail(Guid pageid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a pageDetail");
            DataPortal.Delete(new Criteria(pageid));
        }

        public override PageDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a pageDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a pageDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a pageDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid pageid;

            public Criteria(Guid pageid)
            {
                this.pageid = pageid;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@pageid", criteria.pageid);

            using (SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetPageByPageID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _pageid = dr.GetGuid("pageid");
            _kbid = dr.GetInt32("kbid");
            _createdate = dr.GetSmartDate("createdate", _createdate.EmptyIsMin);
            _publishdate = dr.GetSmartDate("publishdate", _publishdate.EmptyIsMin);
            _expiredate = dr.GetSmartDate("expiredate", _expiredate.EmptyIsMin);
            _statusdate = dr.GetSmartDate("statusdate", _statusdate.EmptyIsMin);
            _currentuserid = dr.GetGuid("currentuserid");
            _title = dr.GetString("title");
            _ivAccessType = dr.GetInt32("iv_access_type");
            _ivLevel = dr.GetInt32("iv_level");
            _ivStatus = dr.GetInt32("iv_status");
            _ivPriority = dr.GetInt32("iv_priority");
            _keywords = dr.GetString("keywords");
            _revision = dr.GetInt32("pagerevision");
            _templateid = dr.GetGuid("templateid");
            _summary = dr.GetString("summary");
            _spotlight = dr.GetBoolean("spotlight");
            _views = dr.GetInt64("views");
            _comments = dr.GetInt32("comments");
            _ivItemtype = dr.GetInt32("iv_itemtype");
            _rank = dr.GetInt32("rank");
            _userid = dr.GetGuid("userid");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertPage.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@pageid", _pageid);
            DAL.AddParameter("@publishdate", _publishdate.DBValue);
            DAL.AddParameter("@expiredate", _expiredate.DBValue);

            if (_title != string.Empty)
                DAL.AddParameter("@title", _title);
            else
                DAL.AddParameter("@title", DBNull.Value);

            if (_ivAccessType != 0)
                DAL.AddParameter("@iv_access_type", _ivAccessType);
            else
                DAL.AddParameter("@iv_access_type", DBNull.Value);

            if (_ivLevel != 0)
                DAL.AddParameter("@iv_level", _ivLevel);
            else
                DAL.AddParameter("@iv_level", DBNull.Value);

            if (_ivStatus != 0)
                DAL.AddParameter("@iv_status", _ivStatus);
            else
                DAL.AddParameter("@iv_status", DBNull.Value);

            if (_templateid != Guid.Empty)
                DAL.AddParameter("@templateid", _templateid);
            else
                DAL.AddParameter("@templateid", DBNull.Value);

            if (_keywords != string.Empty)
                DAL.AddParameter("@keywords", _keywords);
            else
                DAL.AddParameter("@keywords", DBNull.Value);

            if (_summary != string.Empty)
                DAL.AddParameter("@summary", _summary);
            else
                DAL.AddParameter("@summary", DBNull.Value);

            if (_revision != 0)
                DAL.AddParameter("@revision", _revision);
            else
                DAL.AddParameter("@revision", 0);

            if (_ivItemtype != 0)
                DAL.AddParameter("@iv_itemtype", _ivItemtype);
            else
                DAL.AddParameter("@iv_itemtype", DBNull.Value);

            //if (_spotlight != 0)
            DAL.AddParameter("@spotlight", _spotlight);
            //else
            //    DAL.AddParameter("@spotlight", DBNull.Value);

            DAL.AddParameter("@userid", _userid);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdatePage.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@pageid", _pageid);
            DAL.AddParameter("@publishdate", _publishdate.DBValue);
            DAL.AddParameter("@expiredate", _expiredate.DBValue);

            if (_title != string.Empty)
                DAL.AddParameter("@title", _title);
            else
                DAL.AddParameter("@title", DBNull.Value);

            if (_ivAccessType != 0)
                DAL.AddParameter("@iv_access_type", _ivAccessType);
            else
                DAL.AddParameter("@iv_access_type", DBNull.Value);

            if (_ivLevel != 0)
                DAL.AddParameter("@iv_level", _ivLevel);
            else
                DAL.AddParameter("@iv_level", DBNull.Value);

            if (_ivStatus != 0)
                DAL.AddParameter("@iv_status", _ivStatus);
            else
                DAL.AddParameter("@iv_status", DBNull.Value);

            if (_templateid != Guid.Empty)
                DAL.AddParameter("@templateid", _templateid);
            else
                DAL.AddParameter("@templateid", DBNull.Value);

            if (_keywords != string.Empty)
                DAL.AddParameter("@keywords", _keywords);
            else
                DAL.AddParameter("@keywords", DBNull.Value);

            if (_summary != string.Empty)
                DAL.AddParameter("@summary", _summary);
            else
                DAL.AddParameter("@summary", DBNull.Value);

            if (_revision != 0)
                DAL.AddParameter("@revision", _revision);
            else
                DAL.AddParameter("@revision", 0);

            if (_ivItemtype != 0)
                DAL.AddParameter("@iv_itemtype", _ivItemtype);
            else
                DAL.AddParameter("@iv_itemtype", DBNull.Value);

            //if (_spotlight != 0)
            DAL.AddParameter("@spotlight", _spotlight);
            //else
            //    DAL.AddParameter("@spotlight", DBNull.Value);
        }

        //private void UpdateChildren(SqlConnection cn)
        //{
        //}
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_pageid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeletePage.ToString().Trim(), CommandType.Text, ConnectionState.Open);
            Procs.PurgeItemsByItemID(criteria.pageid);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@pageid", criteria.pageid);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
